package com.cts.tmall.app.controller;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cts.tmall.app.request.R;
import com.cts.tmall.app.response.PropSpecResponse;
import com.cts.tmall.app.response.SkuResponse;
import com.cts.tmall.biz.service.PropService;
import com.cts.tmall.biz.service.SkuService;
import com.cts.tmall.biz.service.SpecService;
import com.cts.tmall.com.exception.SystemException;
import com.cts.tmall.com.message.RspCode;
import com.cts.tmall.dal.entity.Prop;
import com.cts.tmall.dal.entity.Spec;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/spec")
public class SpecController {

    @Autowired
    SpecService specService;

    @Autowired
    SkuService skuService;

    @Autowired
    PropService propService;

    @PostMapping("add")
    public R add(@RequestBody Spec spec) {
        if (StrUtil.isBlank(spec.getSpecName())) {
            log.error("规格名称不能为空");
            throw new SystemException(RspCode.FAILURE_SYSTEM);
        }
        if (specService.count(new QueryWrapper<Spec>().eq("prop_no", spec.getPropNo())) > 2) {
            log.error("最多添加3个规格");
            throw new SystemException(RspCode.FAILURE_SYSTEM);
        }
        Snowflake snowflake = IdUtil.createSnowflake(1L, 1L);
        String no = String.valueOf(snowflake.nextId());
        spec.setSpecNo(no);
        specService.save(spec);

        return res(spec.getGoodsNo());
    }

    @PostMapping("del")
    public R del(@RequestBody Spec spec){
        specService.remove(new QueryWrapper<Spec>().eq("spec_no",spec.getSpecNo()));
        return res(spec.getGoodsNo());
    }

    @PostMapping("check")
    public R check(@RequestBody Spec spec){
        specService.update(spec,new QueryWrapper<Spec>().eq("spec_no",spec.getSpecNo()));
        return res(spec.getGoodsNo());
    }

    private R res(String goodNo){
        skuService.reCreateSku(goodNo);
        List<PropSpecResponse> propSpecResponseList = propService.getPropSpec(goodNo);
        List<SkuResponse> skuResponseList = skuService.getSkuList(goodNo);
        return R.ok().put("propList", propSpecResponseList).put("skuList", skuResponseList);
    }

}
